import React, { useState, useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './Header.module.css';

interface UserProfileData {
  userName: string;
  userAvatar: string | null;
  userProfile: string | null;
  nickname?: string;
  avatar?: string;
}

interface HeaderProps {
  currentPage?: string; // 当前页面标识，用于高亮导航
}

const Header: React.FC<HeaderProps> = ({ currentPage }) => {
  const navigate = useNavigate();
  const globalSearchRef = useRef<HTMLInputElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);
  
  const [userProfileData, setUserProfileData] = useState<UserProfileData>({
    userName: '用户',
    userAvatar: null,
    userProfile: null,
    nickname: '用户',
    avatar: 'https://s.coze.cn/image/eSbV8sZ4zMY/'
  });
  
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [isLogoutLoading, setIsLogoutLoading] = useState<boolean>(false);

  // 获取用户信息
  const fetchUserProfile = async () => {
    try {
      const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo');
      let userId = null;
      
      if (userInfo) {
        try {
          const parsedUserInfo = JSON.parse(userInfo);
          userId = parsedUserInfo.id;
        } catch (e) {
          console.error('解析用户信息失败:', e);
        }
      }

      if (!userId) {
        return; // 如果没有用户ID，使用默认数据
      }

      const response = await fetch(`http://localhost:8121/api/user/get/vo?id=${userId}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include'
      });

      const result = await response.json();

      if (response.ok && result.code === 0 && result.data) {
        const userData = result.data;
        const newProfileData: UserProfileData = {
          userName: userData.userName || '用户',
          userAvatar: userData.userAvatar,
          userProfile: userData.userProfile,
          nickname: userData.userName || '用户',
          avatar: userData.userAvatar || 'https://s.coze.cn/image/eSbV8sZ4zMY/'
        };
        
        setUserProfileData(newProfileData);
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }
  };

  // 全局搜索处理
  const handleGlobalSearchKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      const keyword = globalSearchRef.current?.value?.trim();
      if (keyword) {
        navigate(`/search-result?q=${encodeURIComponent(keyword)}`);
      }
    }
  };

  // 退出登录函数
  const handleLogout = async () => {
    if (!confirm('确定要退出登录吗？')) {
      return;
    }

    setIsLogoutLoading(true);

    try {
      // 调用后端退出登录接口
      const response = await fetch('http://localhost:8121/api/user/logout', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include' // 包含cookies，用于session管理
      });

      const result = await response.json();

      if (response.ok && result.code === 0) {
        // 清除本地存储的用户信息
        localStorage.removeItem('userInfo');
        sessionStorage.removeItem('userInfo');
        
        // 清除其他可能的用户相关数据
        localStorage.removeItem('token');
        sessionStorage.removeItem('token');

        // 跳转到登录页面
        navigate('/login', { replace: true });
      } else {
        alert(result.message || '退出登录失败，请重试');
      }
    } catch (error) {
      console.error('退出登录请求失败:', error);
      alert('网络错误，请稍后重试');
    } finally {
      setIsLogoutLoading(false);
    }
  };

  // 获取导航链接的样式
  const getNavLinkClass = (page: string) => {
    const baseClass = "px-4 py-2 rounded-lg text-center";
    if (currentPage === page) {
      return `${baseClass} bg-gradient-to-r from-orange-400 to-orange-600 text-white`;
    }
    return `${baseClass} text-gray-600 hover:text-orange-500`;
  };

  // 处理用户下拉菜单
  const toggleDropdown = () => {
    setIsDropdownOpen(!isDropdownOpen);
  };

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsDropdownOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  useEffect(() => {
    fetchUserProfile();
  }, []);

  return (
    <header className="fixed top-0 left-0 right-0 h-16 bg-white shadow-sm z-50">
      <div className="flex items-center justify-between h-full px-6">
        {/* Logo和产品名称 */}
        <div className="flex items-center space-x-3">
          <div className={`w-10 h-10 ${styles.gradientBg} rounded-xl flex items-center justify-center`}>
            <i className="fas fa-graduation-cap text-white text-lg"></i>
          </div>
          <h1 className="text-xl font-bold text-gray-800">精进坊</h1>
        </div>
        
        {/* 主导航 */}
        <nav className="hidden md:flex items-center space-x-8">
          <Link to="/home" className={getNavLinkClass('home')}>首页</Link>
          <Link to="/cognition-home" className={getNavLinkClass('cognition')}>认知提升</Link>
          <Link to="/fitness-home" className={getNavLinkClass('fitness')}>身体健身</Link>
          <Link to="/learning-home" className={getNavLinkClass('learning')}>学习能力</Link>
        </nav>
        
        {/* 搜索框和用户操作区 */}
        <div className="flex items-center space-x-4">
          {/* 搜索框 */}
          <div className="relative hidden lg:block">
            <input 
              type="text" 
              ref={globalSearchRef}
              placeholder="搜索内容..." 
              onKeyPress={handleGlobalSearchKeyPress}
              className="w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-transparent"
            />
            <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
          </div>
          
          {/* 消息通知 */}
          <button className="relative p-2 text-gray-600 hover:text-orange-500">
            <i className="fas fa-bell text-lg"></i>
            <span className="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full"></span>
          </button>
          
          {/* 用户头像/昵称 */}
          <div className="relative" ref={dropdownRef}>
            <button 
              onClick={toggleDropdown}
              className="flex items-center space-x-2 p-2 rounded-lg hover:bg-gray-100"
            >
              <img 
                src={userProfileData.avatar}
                alt="用户头像" 
                className="w-8 h-8 rounded-full" 
                data-category="人物"
              />
              <span className="hidden md:block text-gray-800 font-medium">{userProfileData.nickname}</span>
              <i className={`fas fa-chevron-down text-xs text-gray-400 transition-transform ${isDropdownOpen ? 'rotate-180' : ''}`}></i>
            </button>
            
            {/* 下拉菜单 */}
            {isDropdownOpen && (
              <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-2 z-50">
                <Link 
                  to="/user-profile" 
                  className="flex items-center px-4 py-2 text-gray-700 hover:bg-gray-100"
                  onClick={() => setIsDropdownOpen(false)}
                >
                  <i className="fas fa-user text-gray-500 w-5"></i>
                  <span className="ml-3">个人中心</span>
                </Link>
                <Link 
                  to="/user-collections" 
                  className="flex items-center px-4 py-2 text-gray-700 hover:bg-gray-100"
                  onClick={() => setIsDropdownOpen(false)}
                >
                  <i className="fas fa-heart text-gray-500 w-5"></i>
                  <span className="ml-3">我的收藏</span>
                </Link>
                <Link 
                  to="/user-history" 
                  className="flex items-center px-4 py-2 text-gray-700 hover:bg-gray-100"
                  onClick={() => setIsDropdownOpen(false)}
                >
                  <i className="fas fa-history text-gray-500 w-5"></i>
                  <span className="ml-3">学习历史</span>
                </Link>
                <div className="border-t border-gray-200 my-2"></div>
                <button 
                  className="flex items-center w-full px-4 py-2 text-gray-700 hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                  onClick={() => {
                    setIsDropdownOpen(false);
                    handleLogout();
                  }}
                  disabled={isLogoutLoading}
                >
                  <i className="fas fa-sign-out-alt text-gray-500 w-5"></i>
                  <span className="ml-3">
                    {isLogoutLoading ? (
                      <>
                        <i className="fas fa-spinner fa-spin mr-1"></i>
                        退出中...
                      </>
                    ) : (
                      '退出登录'
                    )}
                  </span>
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </header>
  );
};

export default Header;